/**
 * 下单
 * @author Qasim <15750783791@163.com>
 * @version 2016/9/19
 */
var self = phone = memberInfo = '';
var pays = {};

document.addEventListener('plusready' , ready ,  false);

function ready(){
	
	self = plus.webview.currentWebview(); 
	
	console.log(self.page) 
	
	memberInfo = plus.storage.getItem('memberInfo');
	
	memberInfo = $.parseJSON(memberInfo);
	
	var uid = memberInfo.uid , nickname = memberInfo.nickname , total_number = self.number;
	
	//获取验证码
	$('.verification').on('click' , function(){
		
		phone = $('input[name=phone]').val();
		
		if(!p1.test(phone)){
			
			toast('手机号码格式有误'); return;
			
		} 
		getverify(phone);
	})
	
	
	
	// 获取支付通道
	plus.payment.getChannels(function(channels){
		var channel=channels[0];
		pays[channel.id]=channel;
		checkServices(channel);
	},function(e){
		toast("获取支付通道失败："+e.message);
	});
	
	
	//下单
	$('.add_tx_order').on('click' , function(){
		var money = $('input[name=money]').val();
		var account = $('input[name=account]').val();
		var verify = $('input[name=verification]').val();
		
		if(!money.trim()){
			toast('提现金额不能为空哦');
			return;
		}
		
		if(parseInt(money * 10) > total_number){
			toast('您的积分不足以提现这么多哦');
			return;
		}
		
		if(!account.trim()){
			toast('支付宝账号不能为空哦');
			return;
		}
		var verify_local = plus.storage.getItem('verify');
		if(!verify_local || verify_local != verify){
			toast('验证码输入有误');return;
		}
		plus.nativeUI.showWaiting('请求中...');
		$.ajax({
			type:"post",
			url:apiRoot +'/Home/Orders/add_order/',
			data:{
				money : money,
				uid: uid,
				name : nickname,
				zfb_account : account,
				phone : phone, 
				tid : 42,
				tx_status : 1,
				title : nickname +'在' + new Date().toLocaleString() + '申请了提现 , 金额: ￥'+money+' 订单号为:'
 			},
			success : function(data){
				plus.nativeUI.closeWaiting();
				plus.storage.removeItem('verify');
				if(data > 0){ 
					$('input[name=money]').val('');
					$('input[name=account]').val('');
					$('input[name=phone]').val('');
					$('input[name=verification]').val('');
					$('.jf-yz-btn').html('<label>验证码：</label><input type="number" name="verification" placeholder="请输入验证码"/><button class="background-zx color-white verification">获取验证码</button>');
					toast('请求成功,等待后台审核'); 
				}
			},
			error : function(e){
				
				console.log(JSON.stringify(e));
				
				plus.nativeUI.closeWaiting();
				
				toast('连接超时,请检查网络');
				
			}
		});
	})
	
	$('.pay-btn').on('tap' , function(){
		if(memberInfo.gid != 3){
			toast('只支持商家用户充值');return;
		}
		var price = $('.price').val();
		if(price.indexOf('.')>=0 || parseInt(price) <= 0 || !price.trim()){
			toast('请输入正整数');return;
		}
		
		var orderid = (Date.parse(new Date()) + '').substr(0,10);
		for(var i=0;i<6;i++) { 
			orderid += Math.floor(Math.random()*10); 
		} 
		pay('alipay' , orderid , price);
	})
}

 
var w = null; 
// 支付
function pay(id , orderid , price){
	if(w){return;}//检查是否请求订单中
	if(id != 'alipay'){ 
		plus.nativeUI.alert("不支持此支付通道！");  
	} 
	var url = payRoot + '?orderid='+orderid+'&price='+price;
	console.log(url);
	w = plus.nativeUI.showWaiting();
	// 请求支付订单
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange=function(){
		switch(xhr.readyState){
			case 4:
				w.close(); w = null;
				if(xhr.status == 200){
					var order = xhr.responseText;
					plus.payment.request(pays[id] , order , function(result){
						plus.nativeUI.alert("支付成功 ",function(){
							addOrder(price , orderid  , 2);
						},"第三方");
					},function(e){
						addOrder(price , orderid  , 1);  
					});
				}else{
					toast( xhr.status );
					plus.nativeUI.alert("获取订单信息失败！");
				}
				break;
			default:  
				break;
		}
	}
	xhr.open('GET',url);
	toast("请求支付订单"); 
	xhr.send();
}


function addOrder(price , orderid , state){
	$.ajax({
		type:"post",
		url:apiRoot +'/Home/Orders/recharge/',
		data:{
			money : price,
			orderid : orderid,
			uid: memberInfo.aid,
			name : memberInfo.nickname,
			tid : 41,
			cz_status : state, 
			title : self.nickname +'在' + new Date().toLocaleString() + '进行了充值 , 金额: ￥'+price+' 订单号为:' + orderid
		},
		success : function(data){ 
			plus.nativeUI.closeWaiting();
			$('.price').val('');
			if(state == 1){
				toast('支付失败') 
			}else if(state == 2){
				console.log(JSON.stringify($.parseJSON(data)))
				toast('积分已到账,请您查收'); 
				plus.storage.setItem('memberInfo' , data+'');
				var cur = plus.webview.getWebviewById(self.page);
				cur.evalJS('addHistory('+price+')'); 
			} 
		},
		error : function(e){
			
			console.log(JSON.stringify(e));
			
			plus.nativeUI.closeWaiting();
			
			toast('连接超时,请检查网络');
			
		}
	});
	
	
	
}


// 检测是否安装支付服务
function checkServices(pc){
	if(!pc.serviceReady){
		var txt=null;
		switch(pc.id){
			case "alipay":
			txt="检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
			break;
			default:
			txt="系统未安装“"+pc.description+"”服务，无法完成支付，是否立即安装？";
			break;
		}
		plus.nativeUI.confirm(txt,function(e){
			if(e.index==0){
				pc.installService();
			}
		},pc.description);
	}
}